package com.sinsz.common.interceptor;

import com.sinsz.common.util.RequestUtils;
import com.sinsz.common.util.SignUtils;
import org.nutz.json.Json;
import org.nutz.json.JsonFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 访问请求日志拦截器
 * @author chenjianbo
 */
public class LogsInterceptor extends HandlerInterceptorAdapter {

    private static final Logger logger = LoggerFactory.getLogger(LogsInterceptor.class);

    private static final String CURRENT_TIME = "_log_info_interceptor";

    @Override
    public boolean preHandle(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler) {
        Long currentTime = System.currentTimeMillis();
        request.setAttribute(SignUtils.signatureSha1(CURRENT_TIME), currentTime);
        return true;
    }

    @Override
    public void afterCompletion(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler, Exception ex) {
        String remoteHost = request.getRemoteHost();
        String requestUri = request.getRequestURI();
        String method = request.getMethod();
        String params = requestParams(request);
        Long currentTime = (Long) request.getAttribute(SignUtils.signatureSha1(CURRENT_TIME));
        currentTime = currentTime == null ? -1L : System.currentTimeMillis() - currentTime;
        logger.info("请求地址:{}, 路径:{}, 请求方式:{}, 请求耗时:{}毫秒, 请求GET参数：[[[ {} ]]] ",remoteHost, requestUri,method, currentTime, params);
    }

    private static String requestParams(HttpServletRequest request) {
        return Json.toJson(RequestUtils.requestParams(request), JsonFormat.tidy());
    }

}
